package com.lagou.rpc.consumer.processor;

import com.lagou.rpc.consumer.annotation.RpcReference;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private RpcClientProxy rpcClientProxy;

    // 前置处理器
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor.postProcessBeforeInitialization");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        System.out.println("MyBeanPostProcessor.postProcessAfterInitialization");
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            RpcReference annotation = declaredField.getAnnotation(RpcReference.class);
            if(annotation == null) continue;
            Object proxy = this.rpcClientProxy.createProxy(declaredField.getType());
            declaredField.setAccessible(true);
            try {
                declaredField.set(bean,proxy);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return bean;
    }
}
